﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Net;

namespace com.crawler.common
{
    public class MyWebRequest
    {
        public int m_timeout;
        public WebHeaderCollection m_headers;
        public string m_header;
        public Uri m_request_uri;
        public string m_method;
        public MyWebResponse m_response;
        public bool m_keep_alive;

        public MyWebRequest(Uri i_uri, bool i_keep_alive)
        {
            m_headers = new WebHeaderCollection();
            m_request_uri = i_uri;
           
            m_headers["Host"] = i_uri.Host;
            m_keep_alive = i_keep_alive;
            if (m_keep_alive)
                m_headers["Connection"] = "Keep-Alive";
            m_method = "GET";
        }
        public static MyWebRequest Create(Uri i_uri, MyWebRequest i_alive_request, bool i_keep_alive)
        {
            if (i_keep_alive &&
                i_alive_request != null &&
                i_alive_request.m_response != null &&
                i_alive_request.m_response.m_keep_alive &&
                i_alive_request.m_response.m_socket.Connected &&
                i_alive_request.m_request_uri.Host == i_uri.Host)
            {
                i_alive_request.m_request_uri = i_uri;
                return i_alive_request;
            }
            return new MyWebRequest(i_uri, i_keep_alive);
        }
        public MyWebResponse GetResponse()
        {
            if (m_response == null || m_response.m_socket == null || m_response.m_socket.Connected == false)
            {
                m_response = new MyWebResponse();
                m_response.Connect(this);
                m_response.SetTimeout(m_timeout);
            }
            m_response.SendRequest(this);
            m_response.ReceiveHeader();
            return m_response;
        }

     
    }
}
